package com.example.demo.pdfbox.factory;

import com.example.demo.pdfbox.common.PdfProcessElement;
import com.example.demo.pdfbox.common.function.ElementProcess;
import com.example.demo.pdfbox.processor.*;
import com.example.demo.pdfbox.tabel.PdfElement;
import com.example.demo.pdfbox.tabel.PdfParagraph;
import com.example.demo.pdfbox.tabel.concrete.PdfGraph;
import com.example.demo.pdfbox.tabel.concrete.PdfLine;
import com.example.demo.pdfbox.tabel.concrete.PdfPicture;
import com.example.demo.pdfbox.tabel.form.PdfForm;
import com.example.demo.pdfbox.tabel.form.PdfRow;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;

import java.io.IOException;

public class ElementHandler {

 public int processElement(PdfProcessElement pdfProcessElement) throws IOException {
  PdfElement element = pdfProcessElement.element;

  if (element instanceof PdfForm) {
   ElementProcess pdfFormProcessor = new PdfFormProcessor();
   return pdfFormProcessor.process(pdfProcessElement);
  } else if (element instanceof PdfParagraph) {
   ElementProcess pdfParagraphProcessor = new PdfParagraphProcessor();
   return pdfParagraphProcessor.process(pdfProcessElement);
  } else if (element instanceof PdfLine) {
   ElementProcess pdfLineProcessor = new PdfLineProcessor();
   return pdfLineProcessor.process(pdfProcessElement);
  } else if (element instanceof PdfPicture) {
   ElementProcess pdfPictureProcessor = new PdfPictureProcessor();
   return pdfPictureProcessor.process(pdfProcessElement);
  } else if (element instanceof PdfRow) {
   ElementProcess pdfRowProcessor = new PdfRowProcessor();
   return pdfRowProcessor.process(pdfProcessElement);
  } else if (element instanceof PdfGraph) {
   PdfGraphProcessor pdfGraphProcessor = new PdfGraphProcessor();
   return pdfGraphProcessor.process(pdfProcessElement);
  } else {
   pdfProcessElement.position.startX += element.getX();
   pdfProcessElement.position.startY -= element.getY();
   if (pdfProcessElement.position.startY <= pdfProcessElement.position.margin.getMarginFoot() && pdfProcessElement.flag) {
    PDPage page = new PDPage(pdfProcessElement.position.rectangle);
    pdfProcessElement.document.addPage(page);
    pdfProcessElement.position.startY = page.getMediaBox().getHeight() - pdfProcessElement.position.margin.getMarginHead();
    pdfProcessElement.contentStream.close();
    pdfProcessElement.contentStream = new PDPageContentStream(pdfProcessElement.document, page);
    return 1;
   }
   return 0;
  }
 }


}
